package com.example.mobile2121606109ycg0527homework;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class MyDataAdapter {
    private MySQLiteOpenHelper openHelper;
    private SQLiteDatabase database;
//    打开数据库
    public void openDB(Context context) {
        openHelper = new MySQLiteOpenHelper(context, "school.db", null, 1);
        try {
            database = openHelper.getWritableDatabase();
        }catch (Exception e){
            database = openHelper.getReadableDatabase();
        }
    }
//    清除数据库
    public void closeDB() {
        if (database != null){
            database.close();
            database = null;
        }
        if (openHelper != null){
            openHelper.close();
            openHelper = null;
        }
    }
//    查询所有数据
    public List<School> QueryAll(Context context){
        List<School> schoolList = new ArrayList<>();
        openDB(context);
        Cursor cursor = database.query("school", null, null, null, null, null, null);
                if (cursor.moveToFirst()){
                    do{
                        int id = cursor.getInt(0);
                        String schoolName = cursor.getString(1);
                        String address = cursor.getString(2);
                        schoolList.add(new School(schoolName, address));
                    }while (cursor.moveToNext());
                }
                cursor.close();
                closeDB();
                return schoolList;
    }
//    添加数据
    public long insert(Context context, School school){
        openDB(context);
        ContentValues values = new ContentValues();
        values.put("schoolName", school.getSchoolName());
        values.put("address", school.getAddress());
        long result = database.insert("school", null, values);
        closeDB();
        return result;
    }
//    修改数据
    public int delete(Context context, String schoolName){
        openDB(context);
        int result = database.delete("school", "schoolName=?", new String[]{schoolName});
        closeDB();
        return result;
    }
//    更新数据
    public int update(Context context, String schoolName, School school){
        openDB(context);
        ContentValues values = new ContentValues();
        values.put("schoolName", school.getSchoolName());
        values.put("address", school.getAddress());
        int result = database.update("school", values, "schoolName=?", new String[]{schoolName});
        closeDB();
        return result;
    }
}
